﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
using System.Windows.Forms.DataVisualization.Charting;

namespace NEMproject
{

    public partial class FormInterface : Form
    {

        Color COLOR_ERROR_TB = Color.Linen;
        Color COLOR_ERROR_TS = Color.RosyBrown; //for tool strip
        Color COLOR_BLACK = SystemColors.Control;
        Color COLOR_WHITE = SystemColors.Window;
        Color COLOR_TEXT_SHADOW = Color.LightGray;

        private NEMmain nemObj;
        //private ParametersWindow parameterWindow;

        static int pressedCalculateButton = 0;
        private Point closeButtonImageSize = new Point(16, 16);
        
        public FormInterface()
        {
            InitializeComponent();
            InitializeComponent1();
            
            //parameterWindow = new ParametersWindow();
            //parameterWindow.loadParameterWindowSettings();

            loadBasicInterfaceSettings();
        }

        #region My Functions

        private void InitializeComponent1()
        {
            nemObj = new NEMmain();
            bindCitiesInComboBox();
  
            PVSystemSizeChanged();
            
        }

        private bool retrieveAndValidateFormData()
        {

            bool checkPassed = true;
            errorProvider_Form.Clear();
            errorProvider_Form.BlinkStyle = ErrorBlinkStyle.NeverBlink;

            int value;
            double dvalue;
                                  
            for (int i = 0; i < nemObj.BIMONTHS; i++) //iterate through masked text boxes
            {
                //Check if all neccessary fields have been given in bimonthly consumptions                
                Control control = findControlByName(this.groupBox_BiMonthCon.Controls, "maskedTextBox_BiMonthCon" + i.ToString() );
                if (control == null) throw new ArgumentNullException("Control: maskedTextBox_BiMonthCon" + i.ToString()+"could not be found");

                value = 0;
                if (Int32.TryParse(control.Text, out value))
                {
                    nemObj.CumHE[i] = value;                    
                }
                else
                {
                    setControlError(control);
                    checkPassed = false;
                }


                //Check if all neccessary fields have been given in solar irradiation 
                control = null;
                control = findControlByName(this.groupBox_SolarIrr.Controls, "maskedTextBox_SolarIrr" + i.ToString());
                if (control == null) throw new ArgumentNullException("Control: maskedTextBox_SolarIrr" + i.ToString() + "could not be found");

                value = 0;
                if (Int32.TryParse(control.Text, out value))
                {
                    nemObj.SolarIrr[i] = value;
                }
                else
                {
                    setControlError(control);
                    checkPassed = false;
                }

            }

            //Set tariff
            if (radioButton_tariff1.Checked) {
                nemObj.Tariff = TARIFFS.Tar05;
            }
            else if (radioButton_tariff2.Checked)
            {
                nemObj.Tariff = TARIFFS.Tar06;
            }
            else if (radioButton_tariff3.Checked)
            {
                nemObj.Tariff = TARIFFS.Tar07;
            }
            else 
            {
                nemObj.Tariff = TARIFFS.Tar08;
            }


            //Check if all neccessary fields have been given in PVSystem 
            dvalue = 0;
            if (Double.TryParse(numericUpDown_PVSize.Text, out dvalue))
            {
                nemObj.pvSystem.PvInstCap = dvalue;
            }
            else
            {
                setControlError(numericUpDown_PVSize);
                checkPassed = false;
            }

            dvalue = 0;
            if (Double.TryParse(maskedTextBox_PVArea.Text, out dvalue))
            {
                nemObj.pvSystem.PvArea = dvalue;
            }
            else
            {
                setControlError(maskedTextBox_PVArea);
                checkPassed = false;
            }

            value = 0;
            if (Int32.TryParse(numericUpDown_yearHorizon.Text, out value))
            {
                nemObj.YearHorizon = value;
            }
            else
            {
                setControlError(numericUpDown_yearHorizon);
                checkPassed = false;
            }

            dvalue = 0;
            if (Double.TryParse( maskedTextBox_InitialCost.Text, out dvalue))
            {
                nemObj.pvSystem.PvInitialCost = dvalue;
            }
            else
            {
                setControlError(maskedTextBox_InitialCost);
                checkPassed = false;
            }

            dvalue = 0;
            if (Double.TryParse(maskedTextBox_AnnualMaint.Text, out dvalue))
            {
                nemObj.pvSystem.PvAnnualMaintCost = value;
            }
            else
            {
                setControlError(maskedTextBox_AnnualMaint);
                checkPassed = false;
            }

            if (numericUpDown_PVEfficiency.Value > 0)
            {
                nemObj.pvSystem.PvEfficiancy = (double)numericUpDown_PVEfficiency.Value / 100;
            }
            else
            {
                setControlError(numericUpDown_PVEfficiency);
                checkPassed = false;
            }

            if (numericUpDown_PVLosses.Value > 0)
            {
                nemObj.pvSystem.PvLosses = (double)numericUpDown_PVLosses.Value / 100;
            }
            else
            {
                setControlError(numericUpDown_PVLosses);
                checkPassed = false;
            }

            if (numericUpDown_PVDegradation.Value > 0)
            {
                nemObj.pvSystem.PvDegradation = (double)numericUpDown_PVDegradation.Value / 100;
            }
            else
            {
                setControlError(numericUpDown_PVDegradation);
                checkPassed = false;
            }

            if (numericUpDown_discountRate.Value > 0)
            {
                nemObj.DiscountRate = (double)numericUpDown_discountRate.Value / 100;
            }
            else
            {
                setControlError(numericUpDown_discountRate);
                checkPassed = false;
            }

            nemObj.EnerCredTransferable = checkBox_energyCredTransf.Checked;


            return checkPassed;           
        }

        /// <summary>
        /// Retrieves the cities from the database and binds them to the combobox.
        /// </summary>
        private void bindCitiesInComboBox()
        {
            DataTable dt = DataRequest.getCities();

            comboBox_Capitals.Items.Clear();
            comboBox_Capitals.DataSource = new BindingSource(dt, null);
            comboBox_Capitals.DisplayMember = "City";            
            comboBox_Capitals.Text = "";
            comboBox_Capitals.SelectedIndex = comboBox_Capitals.FindStringExact("Nicosia",0);

        }


        /// <summary>
        /// Adds all integers in bimonthly masked textboxes
        /// </summary>
        /// <returns>The annual bimonthly consumption</returns>
        private int getAnnualConsumption()
        {

            int annualConsumption = 0;
            foreach (Control control in this.tableLayoutPanel_BiMonthCon.Controls)
            {

                if (control is MaskedTextBox)
                {//foreach maskedTextBox
                    int value = 0;
                    if (Int32.TryParse(control.Text, out value))
                    {//consider only the value of valid textboxes
                        annualConsumption += value;
                    }
                }
            }
            return annualConsumption;
        }

        /// <summary>
        /// reset all cotrols to their intitial state.
        /// </summary>
        /// <param name="parentControl"></param>
        private void resetControls(Control parentControl)
        {

            //bimonthly consumption controls
            maskedTextBox_BiMonthCon0.Text = "";
            setControlNormal(maskedTextBox_BiMonthCon0);
            maskedTextBox_BiMonthCon1.Text = "";
            setControlNormal(maskedTextBox_BiMonthCon1);
            maskedTextBox_BiMonthCon2.Text = "";
            setControlNormal(maskedTextBox_BiMonthCon2);
            maskedTextBox_BiMonthCon3.Text = "";
            setControlNormal(maskedTextBox_BiMonthCon3);
            maskedTextBox_BiMonthCon4.Text = "";
            setControlNormal(maskedTextBox_BiMonthCon4);
            maskedTextBox_BiMonthCon5.Text = "";
            setControlNormal(maskedTextBox_BiMonthCon5);

            textBox_BiMonthCon.Text = "0";

            //pv system controls
            numericUpDown_PVSize.Text = "";
            setControlNormal(numericUpDown_PVSize);

            maskedTextBox_PVArea.Text = "";
            setControlNormal(maskedTextBox_PVArea);

            numericUpDown_PVEfficiency.Value = 0;
            numericUpDown_PVLosses.Value = 0;
            numericUpDown_PVDegradation.Value = 0;

            numericUpDown_yearHorizon.Text = "";
            setControlNormal(numericUpDown_yearHorizon);

            maskedTextBox_InitialCost.Text = "";
            setControlNormal(maskedTextBox_InitialCost);

            maskedTextBox_AnnualMaint.Text = "";
            setControlNormal(maskedTextBox_AnnualMaint);

            numericUpDown_discountRate.Value = 0;
            checkBox_energyCredTransf.Checked = false;

            //solar irradiation controls
            comboBox_Capitals.Text = "";

            maskedTextBox_SolarIrr0.Text = "";
            setControlNormal(maskedTextBox_SolarIrr0);
            maskedTextBox_SolarIrr1.Text = "";
            setControlNormal(maskedTextBox_SolarIrr1);
            maskedTextBox_SolarIrr2.Text = "";
            setControlNormal(maskedTextBox_SolarIrr2);
            maskedTextBox_SolarIrr3.Text = "";
            setControlNormal(maskedTextBox_SolarIrr3);
            maskedTextBox_SolarIrr4.Text = "";
            setControlNormal(maskedTextBox_SolarIrr4);
            maskedTextBox_SolarIrr5.Text = "";
            setControlNormal(maskedTextBox_SolarIrr5);

            //tool Strip Label
            toolStripStatusLabelInfo.ForeColor = COLOR_BLACK;
            toolStripStatusLabelInfo.Text = "Please fill in the details in the above form!!";

        }

       
        /// <summary>
        /// Given a collection of controls and a name of a control this function iterates through all cotrols recursively until the 
        /// the specified name  is found
        /// </summary>
        /// <param name="controlCollection">The intitial collection of controls</param>
        /// <param name="controlName">The name of the control to be found</param>
        /// <returns></returns>
        private static Control findControlByName(Control.ControlCollection controlCollection, string controlName)
        {
            foreach (Control ctrl in controlCollection)
            {
                if (ctrl.Name.Equals(controlName))
                {
                    return ctrl;
                }

                if (ctrl.Controls.Count > 0)
                {
                    Control result = findControlByName(ctrl.Controls, controlName);
                    if (result != null)
                    {
                        return result;
                    }
                }
            }
            return null;
        }

        private static Control findControlByType(Control.ControlCollection controlCollection, Type type)        
        {
            foreach (Control ctrl in controlCollection)
            {
                if (ctrl.GetType() == type)
                {
                    return ctrl;                
                }

                if (ctrl.Controls.Count > 0)
                {
                    Control result = findControlByType(ctrl.Controls, type);
                    if (result != null)
                    {
                        return result;
                    }
                }
            }
            return null;
        }

        private void setControlError(Control control)
        {
            control.BackColor = COLOR_ERROR_TB;
            errorProvider_Form.SetError(control, "This field is required");//set error
        }

        private void setControlNormal(Control control)
        {
            //if (control is TextBox || control is MaskedTextBox)
            //{
            control.BackColor = SystemColors.Window;
            //}

            errorProvider_Form.SetError(control, "");//clear error
        }

        private void PVSystemSizeChanged() 
        { 
            if (radioButton_tariff1.Checked)
            {
                maskedTextBox_PVArea.Text = ((double)numericUpDown_PVSize.Value * 7.03).ToString();
                numericUpDown_PVEfficiency.Value = 14;
                numericUpDown_PVLosses.Value = 18;
                numericUpDown_PVDegradation.Value = 0.75m;
                
            }
        
        }
        /// <summary>
        /// Creates a new output tab and returns it to the caller.
        /// </summary>
        private Object createNewTabOutputPage()
        {
            pressedCalculateButton++;

            //create new tab
            SplitContainer newSplitCont = new System.Windows.Forms.SplitContainer();
            TabPage newTabPage = new System.Windows.Forms.TabPage();
            TextBox newTextBox = new System.Windows.Forms.TextBox();
            Chart newChart = new Chart();

            // 
            // tabControl_Output
            // 
            this.tabControl_Output.Controls.Add(newTabPage); //add the tab to the tabControl
            this.tabControl_Output.SelectedTab = newTabPage; //set the current tab
               
            // 
            // newTabPage
            // 
            newTabPage.Controls.Add(newSplitCont);               
            newTabPage.Name = "ResultSet" + pressedCalculateButton.ToString();
            newTabPage.Text = "ResultSet" + pressedCalculateButton.ToString() + "    ";
            newTabPage.UseVisualStyleBackColor = true;
            newTabPage.ImageIndex = 0;

            //
            //SplitContainer
            //
            newSplitCont.Dock = System.Windows.Forms.DockStyle.Fill;
            newSplitCont.Orientation = Orientation.Horizontal;            
            newSplitCont.Panel1.Controls.Add(newTextBox);           
            newSplitCont.Panel2.Controls.Add(newChart);
            //resize container to proper size

            // 
            // newTextBox
            // 
            newTextBox.Name = "textBoxOutput" + pressedCalculateButton.ToString();
            newTextBox.Dock = DockStyle.Fill;           
            newTextBox.Multiline = true;           
            newTextBox.ScrollBars = ScrollBars.Both;
            newTextBox.WordWrap = false;
            newTextBox.ReadOnly = true;
            newTextBox.BackColor = Color.White;
            
            //
            //newChart
            //
            ChartArea chartArea = new ChartArea();
            Legend legend = new Legend();

            ((System.ComponentModel.ISupportInitialize)(newChart)).BeginInit();

            newChart.Dock = DockStyle.Fill;
            chartArea.Name = "ChartArea" + pressedCalculateButton.ToString();
            newChart.ChartAreas.Add(chartArea);
            legend.Name = "Legend" + pressedCalculateButton.ToString();            
            newChart.Legends.Add(legend);
            newChart.Location = new System.Drawing.Point(3, 3);
            newChart.Name = "chart" + pressedCalculateButton.ToString();

            newChart.Text = "chart1";
            ((System.ComponentModel.ISupportInitialize)(newChart)).EndInit();

            return newSplitCont;
           
        }

       
        private void loadBasicInterfaceSettings()
        {
            this.textBox_BiMonthCon.Text = Properties.BasicInterfaceSettings.Default.textBox_BiMonthCon;
            this.maskedTextBox_BiMonthCon0.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon0;
            this.maskedTextBox_BiMonthCon1.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon1;
            this.maskedTextBox_BiMonthCon2.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon2;
            this.maskedTextBox_BiMonthCon3.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon3;
            this.maskedTextBox_BiMonthCon4.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon4;
            this.maskedTextBox_BiMonthCon5.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon5;

            this.numericUpDown_PVSize.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst0;
            this.maskedTextBox_PVArea.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst1;
            this.numericUpDown_yearHorizon.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst2;
            this.maskedTextBox_InitialCost.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst3;
            this.maskedTextBox_AnnualMaint.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst4;
            this.numericUpDown_PVEfficiency.Value = Properties.BasicInterfaceSettings.Default.numericUpDown_PVSyst0;
            this.numericUpDown_PVLosses.Value = Properties.BasicInterfaceSettings.Default.numericUpDown_PVSyst1;
            this.numericUpDown_PVDegradation.Value = Properties.BasicInterfaceSettings.Default.numericUpDown_PVSyst2;

            this.numericUpDown_discountRate.Value = Properties.BasicInterfaceSettings.Default.numericUpDown_discountRate;
            this.checkBox_energyCredTransf.Checked = Properties.BasicInterfaceSettings.Default.checkBox_energyCredTransf;

            this.comboBox_Capitals.Text = Properties.BasicInterfaceSettings.Default.comboBox_Capitals;
            this.maskedTextBox_SolarIrr0.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr0;
            this.maskedTextBox_SolarIrr1.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr1;
            this.maskedTextBox_SolarIrr2.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr2;
            this.maskedTextBox_SolarIrr3.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr3;
            this.maskedTextBox_SolarIrr4.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr4;
            this.maskedTextBox_SolarIrr5.Text = Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr5;

        }

        private void saveBasicInterfaceSettings()
        {
            Properties.BasicInterfaceSettings.Default.textBox_BiMonthCon = this.textBox_BiMonthCon.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon0 = this.maskedTextBox_BiMonthCon0.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon1 = this.maskedTextBox_BiMonthCon1.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon2 = this.maskedTextBox_BiMonthCon2.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon3 = this.maskedTextBox_BiMonthCon3.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon4 = this.maskedTextBox_BiMonthCon4.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_BiMonthCon5 = this.maskedTextBox_BiMonthCon5.Text;

            Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst0 = this.numericUpDown_PVSize.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst1 = this.maskedTextBox_PVArea.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst2 = this.numericUpDown_yearHorizon.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst3 = this.maskedTextBox_InitialCost.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_PVSyst4 = this.maskedTextBox_AnnualMaint.Text;
            Properties.BasicInterfaceSettings.Default.numericUpDown_PVSyst0 = this.numericUpDown_PVEfficiency.Value;
            Properties.BasicInterfaceSettings.Default.numericUpDown_PVSyst1 = this.numericUpDown_PVLosses.Value;
            Properties.BasicInterfaceSettings.Default.numericUpDown_PVSyst2 = this.numericUpDown_PVDegradation.Value;

            Properties.BasicInterfaceSettings.Default.numericUpDown_discountRate = this.numericUpDown_discountRate.Value;
            Properties.BasicInterfaceSettings.Default.checkBox_energyCredTransf = this.checkBox_energyCredTransf.Checked;

            Properties.BasicInterfaceSettings.Default.comboBox_Capitals = this.comboBox_Capitals.Text.ToString();
            Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr0 = this.maskedTextBox_SolarIrr0.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr1 = this.maskedTextBox_SolarIrr1.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr2 = this.maskedTextBox_SolarIrr2.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr3 = this.maskedTextBox_SolarIrr3.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr4 = this.maskedTextBox_SolarIrr4.Text;
            Properties.BasicInterfaceSettings.Default.maskedTextBox_SolarIrr5 = this.maskedTextBox_SolarIrr5.Text;

            Properties.BasicInterfaceSettings.Default.Save();
        }

        #endregion




        private void button_Calculate_Click(object sender, EventArgs e)
        {
            button_Calculate.Enabled = false;
            bool checkPassed = retrieveAndValidateFormData();

            if (!checkPassed)
            {
                toolStripStatusLabelInfo.Text = "Please fill in all required input..";
                toolStripStatusLabelInfo.ForeColor = COLOR_ERROR_TS;
            }
            else
            {
                try
                {
                    //call main and get the results in struct
                    Output result = nemObj.runMain();
                    SplitContainer splitContainer = (SplitContainer)createNewTabOutputPage();

                    Control _textBox = findControlByType(splitContainer.Panel1.Controls, typeof(TextBox));
                    if (_textBox == null) throw new ArgumentNullException("Control could not be found");
                    TextBox textBox = (TextBox)_textBox;

                    Control _chart = findControlByType(splitContainer.Panel2.Controls, typeof(Chart));
                    if (_chart == null) throw new ArgumentNullException("Control could not be found");
                    Chart newChart = (Chart)_chart;

                    //
                    //TextBox
                    //
                    textBox.AppendText( DateTime.Now.ToString() + "\n");
                    textBox.AppendText("---------------------------------------\n");
                    textBox.AppendText("YearHorizon = " + result.yearHorizon.ToString() + "\n");
                    
                    //totalSavings
                    textBox.AppendText("TotalSavings = [ ");
                    for (int year = 0; year < result.yearHorizon; year++)
                    {
                        textBox.AppendText( Math.Round(result.totalSavings[year], 1).ToString() );
                        if (year < result.yearHorizon - 1)
                        {
                            textBox.AppendText(", ");
                        }
                    }
                    textBox.AppendText(" ]" + "\n");
                    textBox.AppendText("NetPresentValue = " + Math.Round(result.netPresentValue, 2).ToString() + "\n");

                    //
                    //Chart
                    //
                    newChart.Series.Clear();

                    Series series = new Series
                    {
                        Name = "Series1",
                        Color = System.Drawing.Color.Blue,
                        IsVisibleInLegend = true,
                        IsXValueIndexed = true,
                        ChartType = SeriesChartType.RangeColumn
                    };

                    newChart.Series.Add(series);

                    double y = -result.initialCost;;
                    for (int year = 0; year < result.yearHorizon; year++)
                    {
                        series.Points.AddXY(year+1, y);
                        y += result.totalSavings[year];
                    }
                    //newChart.Invalidate();

                }
                catch(Exception exc) 
                {
                    //catch exception and show dialog box
                    MessageBox.Show("Unexpected error occured. " + exc.Message,
                       "Critical Warning",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error,
                       MessageBoxDefaultButton.Button1,
                       MessageBoxOptions.DefaultDesktopOnly);
                }
            }

            button_Calculate.Enabled = true;
        }
        
        private void removeErrorWhenFocused_Enter(object sender, EventArgs e)
        {
            setControlNormal((Control)sender);
        }       

        private void button_Reset_Click(object sender, EventArgs e)
        {
            resetControls(panel_Input);
        }
       
        private void saveConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog.Title = "Save current specifications?";
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            saveFileDialog.RestoreDirectory = true;

            saveFileDialog.Filter = "NEM files (*.nem)|*.nem";
            saveFileDialog.FilterIndex = 0;
           
            var dialogResult = saveFileDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                FormSerializer.SaveState(this, saveFileDialog.FileName);
            }
        }

        private void loadConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.Title = "Open pre-existing configuration file.";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            saveFileDialog.RestoreDirectory = true;
            openFileDialog.Filter = "NEM files (*.nem)|*.nem";
            openFileDialog.FilterIndex = 0;
            var dialogResult = openFileDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                FormSerializer.LoadState(this, openFileDialog.FileName);
            }
        }

        private void parametersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //parameterWindow.ShowDialog();
        }

        private void testdatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NEMproject.SQLiteDatabase dg = new NEMproject.SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<String, String>();
            data.Add("test1", "1");
            try
            {
                Console.WriteLine("Calling insert....");
                dg.Insert("test", data);
                String query = "select test1 from test;";
                DataTable result = dg.GetDataTable(query);

                foreach (DataRow r in result.Rows)
                {
                    Console.WriteLine(r["test1"].ToString());
                }

            }
            catch (Exception crap)
            {
                MessageBox.Show(crap.Message);
            }
        }

        /// <summary>
        /// Fills the Sollar Irradiation data based on the user specified city.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_Capitals_SelectedItemChanged(object sender, EventArgs e)
        {
            DataRowView city = ((DataRowView)comboBox_Capitals.SelectedItem);
            int[] hopt = DataRequest.getHopt(city[0].ToString());

            for (int i = 0; i < nemObj.BIMONTHS; i++)
            {
                Control control = findControlByName(this.groupBox_SolarIrr.Controls, "maskedTextBox_SolarIrr" + i.ToString());
                if (control == null) throw new ArgumentNullException("Control: maskedTextBox_SolarIrr" + i.ToString() + "could not be found");

                if (hopt.Length != 2 * nemObj.BIMONTHS)
                {
                    throw new IndexOutOfRangeException();
                }
                else
                {
                    control.Text = ( hopt[i * 2] + hopt[i * 2 + 1] ).ToString();
                }
            }
        }


        private void FormInterface_FormClosing(object sender, FormClosingEventArgs e)
        {            
            //when windows is shutting down the program dont save anything on close
            if (e.CloseReason == CloseReason.WindowsShutDown) return;                   
            saveBasicInterfaceSettings();                       
        }

        private void maskedTextBox_BiMonthCon_Leave(object sender, EventArgs e)
        {
            textBox_BiMonthCon.Text = getAnnualConsumption().ToString();
        }

        private void numericUpDown_PVSize_ValueChanged(object sender, EventArgs e)
        {
            PVSystemSizeChanged();
        }

        private void tabControl_Output_DrawItem(object sender, DrawItemEventArgs e)
        {
            Point imgHitArea = new Point(13, 13);

            Brush TitleBrush = new SolidBrush(Color.Black);
            Font f = this.Font;
            string title = this.tabControl_Output.TabPages[e.Index].Text;

            //Close Image to draw
            Image image = NEMproject.Properties.Resources.CloseButton;

            Rectangle tabRect = this.tabControl_Output.GetTabRect(e.Index);
            Pen pen = new System.Drawing.Pen(System.Drawing.Color.Black);

            e.Graphics.DrawString(title, f, TitleBrush, new PointF(tabRect.X + 2, tabRect.Y + 3));            
            e.Graphics.DrawImage(image, new Point(tabRect.X + (tabRect.Width - closeButtonImageSize.X - 2), tabRect.Y + (tabRect.Height - closeButtonImageSize.Y - 1)));
           
        }


        private void tabControl_Output_MouseUp(object sender, MouseEventArgs e)
        {
           
            TabControl tabControl = (TabControl)sender;
            Point p = e.Location;

            Rectangle tabRect = tabControl.GetTabRect(tabControl.SelectedIndex);
            Rectangle imageRect = new Rectangle(tabRect.X + (tabRect.Width - closeButtonImageSize.X - 1), tabRect.Y + (tabRect.Height - closeButtonImageSize.Y), closeButtonImageSize.X - 2, closeButtonImageSize.Y - 2);

            if (imageRect.Contains(p))
            {
                TabPage TabPage = (TabPage)tabControl.TabPages[tabControl.SelectedIndex];
                tabControl.TabPages.Remove(TabPage);
            } 
        }

       
    }
}
